
package com.seo.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.seo.pojo.ReturnBody;

import cn.hutool.core.lang.PatternPool;
import cn.hutool.core.util.ReUtil;

/**
 * CommonUtil
 * 
 * @author Administrator
 * @version 2017.12.01 11:40
 */
public class CommonUtil {

	private static class DocumentHolder {
		private static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		static {
			try {
				documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
				documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
				documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
				documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
						false);
				documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
				documentBuilderFactory.setXIncludeAware(false);
				documentBuilderFactory.setExpandEntityReferences(false);
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			}
		}
	}

	public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
		return DocumentHolder.documentBuilderFactory.newDocumentBuilder();
	}

	public static Document newDocument() throws ParserConfigurationException {
		return DocumentHolder.documentBuilderFactory.newDocumentBuilder().newDocument();
	}

	/**
	 * 返回MD5编码
	 * 
	 * @return 返回MD5编码
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String getNonceStr() {
		Random random = new Random();
		return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
	}

	/**
	 * 返回时间戳
	 * 
	 * @return 返回时间戳
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String getTimeStamp() {
		return String.valueOf(System.currentTimeMillis() / 1000);
	}

	/**
	 * map转xml
	 * 
	 * @param vo          vo
	 * @param rootElement rootElement
	 * @return 返回xml
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String map2xmlBody(Map<String, String> data, String rootElement) {
		String output = "";
		try {
			Document document = newDocument();
			Element root = document.createElement(rootElement);
			document.appendChild(root);
			for (String key : data.keySet()) {
				String value = data.get(key);
				if (value == null) {
					value = "";
				}
				value = value.trim();
				Element filed = document.createElement(key);
				filed.appendChild(document.createTextNode(value));
				root.appendChild(filed);
			}
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			DOMSource source = new DOMSource(document);
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			StringWriter writer = new StringWriter();
			StreamResult result = new StreamResult(writer);
			transformer.transform(source, result);
			output = writer.getBuffer().toString();
			writer.close();
		} catch (Exception ex) {
		}
		return output;
	}

	/**
	 * xml转map
	 * 
	 * @param xml         xml
	 * @param rootElement rootElement
	 * @return 返回map
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static Map<String, String> xmlBody2map(String xml, String rootElement) {
		Document doc;
		Map<String, String> data = new TreeMap<>();
		try {
			DocumentBuilder docBuilder = newDocumentBuilder();
			InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
			doc = docBuilder.parse(stream);

			stream.close();
			doc.getDocumentElement().normalize();
			NodeList nodeList = doc.getDocumentElement().getChildNodes();
			for (int idx = 0; idx < nodeList.getLength(); ++idx) {
				Node node = nodeList.item(idx);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					Element element = (Element) node;
					data.put(element.getNodeName(), element.getTextContent());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return data;
	}

	/**
	 * utf-8转码
	 * 
	 * @param str str
	 * @param en  en
	 * @return utf-8转码
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String encode(String str, String en) {
		if (StringUtils.isNotEmpty(str)) {
			try {
				return URLEncoder.encode(str, en);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return "";
			}
		} else {
			return "";
		}
	}

	/**
	 * utf-8转码
	 * 
	 * @param str str
	 * @param en  en
	 * @return utf-8转码
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String decode(String str, String en) {
		if (StringUtils.isNotEmpty(str)) {
			try {
				return URLDecoder.decode(str, en);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return "";
			}
		} else {
			return "";
		}

	}

	/**
	 * makeDisInfo
	 * 
	 * @param min min
	 * @param max max
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static void makeDisInfo(double min, double max) {
		BigDecimal minB = new BigDecimal(min).setScale(2, BigDecimal.ROUND_HALF_DOWN);
		BigDecimal maxB = new BigDecimal(max).setScale(2, BigDecimal.ROUND_HALF_DOWN);
		BigDecimal temp = minB;
		BigDecimal max8 = new BigDecimal("8");

		BigDecimal pointsRatio = new BigDecimal("100");
		BigDecimal points2 = new BigDecimal("2");
		BigDecimal points6 = new BigDecimal("6");
		BigDecimal points7 = new BigDecimal("7");
		BigDecimal points8 = new BigDecimal("8");
		BigDecimal points85 = new BigDecimal("8.5");
		BigDecimal points9 = new BigDecimal("9");

		BigDecimal offlineRatio = new BigDecimal("100");
		BigDecimal offline8 = new BigDecimal("8");
		BigDecimal offline83 = new BigDecimal("8.3");
		BigDecimal offline85 = new BigDecimal("8.5");
		BigDecimal offline88 = new BigDecimal("8.8");
		BigDecimal offline9 = new BigDecimal("9.0");
		BigDecimal offline95 = new BigDecimal("9.5");
		while (temp.compareTo(maxB) <= 0) {

			BigDecimal pRatio = new BigDecimal("0.1");
			BigDecimal cRatio = new BigDecimal("1");
			if (temp.compareTo(max8) < 0) {
				cRatio = max8.subtract(temp).multiply(new BigDecimal("5")).setScale(0, BigDecimal.ROUND_DOWN)
						.add(new BigDecimal("1"));
			}

			if (temp.compareTo(points2) >= 0 && temp.compareTo(points6) <= 0) {
				pointsRatio = new BigDecimal("100");
			} else if (temp.compareTo(points6) > 0 && temp.compareTo(points7) <= 0) {
				pointsRatio = new BigDecimal("50");
			} else if (temp.compareTo(points7) > 0 && temp.compareTo(points8) <= 0) {
				pointsRatio = new BigDecimal("30");
			} else if (temp.compareTo(points8) > 0 && temp.compareTo(points85) <= 0) {
				pointsRatio = new BigDecimal("10");
			} else if (temp.compareTo(points85) > 0 && temp.compareTo(points9) <= 0) {
				pointsRatio = new BigDecimal("5");
			} else {
				pointsRatio = new BigDecimal("0");
			}

			if (temp.compareTo(offline8) <= 0) {
				offlineRatio = new BigDecimal("100");
			} else if (temp.compareTo(offline8) > 0 && temp.compareTo(offline83) <= 0) {
				offlineRatio = new BigDecimal("80");
			} else if (temp.compareTo(offline83) > 0 && temp.compareTo(offline85) <= 0) {
				offlineRatio = new BigDecimal("65");
			} else if (temp.compareTo(offline85) > 0 && temp.compareTo(offline88) <= 0) {
				offlineRatio = new BigDecimal("50");
			} else if (temp.compareTo(offline88) > 0 && temp.compareTo(offline9) <= 0) {
				offlineRatio = new BigDecimal("35");
			} else if (temp.compareTo(offline9) > 0 && temp.compareTo(offline95) <= 0) {
				offlineRatio = new BigDecimal("10");
			}

			StringBuffer sb = new StringBuffer();
			sb.append("insert into hltx_bonus_config(discount,p_ratio,c_ratio,points_ratio,offline_ratio)")
					.append("values(").append(temp).append(",").append(pRatio).append(",").append(cRatio).append(",")
					.append(pointsRatio).append(",").append(offlineRatio).append(");");

			System.out.println(sb.toString());

			temp = temp.add(new BigDecimal("0.01"));
		}

	}

	/**
	 * 获取本地ip
	 * 
	 * @param isLinux isLinux
	 * @return 返回ip
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String getLocalIP(boolean isLinux) {
		String ip = "";
		try {
			if (isLinux) {
				Enumeration<?> e1 = (Enumeration<?>) NetworkInterface.getNetworkInterfaces();
				while (e1.hasMoreElements()) {
					NetworkInterface ni = (NetworkInterface) e1.nextElement();
					if (!ni.getName().equals("eth0")) {
						continue;
					} else {
						Enumeration<?> e2 = ni.getInetAddresses();
						while (e2.hasMoreElements()) {
							InetAddress ia = (InetAddress) e2.nextElement();
							if (ia instanceof Inet6Address) {
								continue;
							}
							ip = ia.getHostAddress();
						}
						break;
					}
				}
			} else {
				ip = InetAddress.getLocalHost().getHostAddress().toString();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return ip;
	}

	/**
	 * 获取UUID
	 * 
	 * @return 返回UUID
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String getUUID() {
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		return uuid;
	}

	public static ReturnBody isUrlGroup(String content) {
		ReturnBody rb = ReturnBody.init();
		// String r =
		// "(https?://)?([\\w-]+\\.)+[\\w-]+((/[\\w-]+)*/[\\w-]+(\\.[\\w-]+)?(\\?[\\w-]+=([%]*[\\w-:\\.]*)*(&[\\w-]+=([%]*[\\w-:\\.]*)*)*)?)?";
		String r = "(https?://)?([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
		String[] strs = content.split("\n");
		if (strs != null && strs.length > 0) {
			List<String> urlList = new ArrayList<>();

			for (int i = 0; i < strs.length; i++) {
				String str = strs[i];
				if (!ReUtil.isMatch(r, str)) {
					return rb.error("第" + (i + 1) + "行（" + str + "）域名格式有误");
				}
				String url = str.replaceFirst("(https?://)", "");
				urlList.add(url);
			}
			rb.put("urlList", urlList);
			return rb.success();
		}
		return rb.error("上传格式有误");
	}

	public static ReturnBody isKeywordGroup(String content, String sp) {
		ReturnBody rb = ReturnBody.init();
		String regex = "[\\S]+";
		String[] strs = content.split(sp);
		if (strs != null && strs.length > 0) {
			List<String> keywordList = new ArrayList<>();
			for (int i = 0; i < strs.length; i++) {
				String str = strs[i];
				if (!ReUtil.isMatch(regex, str)) {
					return rb.error("第" + (i + 1) + "行（" + str + "）关键词格式有误");
				}
				keywordList.add(str);
			}
			rb.put("keywordList", keywordList);
			return rb.success();
		}

		return rb.error("上传格式有误");
	}

	public static ReturnBody isUrlKeywordGroup(String content) {
		ReturnBody rb = ReturnBody.init();
		String r = "[\\S]+[ \t](https?://)?([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
		String[] strs = content.split("\n");

		if (strs != null && strs.length > 0) {
			List<String> urlList = new ArrayList<>();
			List<String> keywordList = new ArrayList<>();

			for (int i = 0; i < strs.length; i++) {
				String str = strs[i];
				if (!ReUtil.isMatch(r, str)) {
					return rb.error("第" + (i + 1) + "行（" + str + "）格式有误");
				}
				String attr[] = StringUtils.split(str, "[ \t]", 2);
				String url = attr[1].replaceFirst("(https?://)", "");
				String keyword = attr[0];
				urlList.add(url);
				keywordList.add(keyword);
			}
			rb.put("urlList", urlList);
			rb.put("keywordList", keywordList);
			return rb.success();
		}
		return rb.error("上传格式有误");
	}

	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[1-9][0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	public static Integer getIntegerByObject(Object object) {
		Integer in = null;

		if (object != null) {
			if (object instanceof Integer) {
				in = (Integer) object;
			} else if (object instanceof String) {
				in = Integer.parseInt((String) object);
			} else if (object instanceof Double) {
				in = (int) ((double) object);
			} else if (object instanceof Float) {
				in = (int) ((float) object);
			} else if (object instanceof BigDecimal) {
				in = ((BigDecimal) object).intValue();
			} else if (object instanceof Long) {
				in = ((Long) object).intValue();
			}
		}

		return in;
	}

	public static void main(String args[]) {
		Integer a = 146;
		int b = 146;

		System.out.println(a.equals(b));
	}
}